'use strict';

const Service = require('egg').Service;

class WechatService extends Service {
  // 获取 ACCESS_TOKEN
  async getAccessToken() {
    const { ctx, app } = this;
    const { appid, appSecret } = app.config.wechat_config;
    const baseUrl = 'https://api.weixin.qq.com/cgi-bin/token';
    const accessTokenUrl = `${baseUrl}?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
    const result = await ctx.curl(accessTokenUrl, { dataType: 'json' });
    if (result.data.hasOwnProperty('errcode')) {
      this.ctx.logger.error(`获取access_token报错！errcode:${result.data.errcode}, errmsg:${result.data.errmsg}`);
      return null;
    }
    return result.data['access_token'];
  }

  // 创建菜单
  async createMenu() {
    const { app } = this;
    const accessToken = await this.getAccessToken();
    if (accessToken) {
      const baseUrl = "https://api.weixin.qq.com/cgi-bin/menu/create"
      const menuCreateUrl = `${baseUrl}?access_token=${accessToken}`
      const result = await this.ctx.curl(menuCreateUrl, {
        dataType: 'json',
        contentType: 'json',
        method: 'POST',
        data: {
          'button': [
            {
              'type': 'view',
              'name': '百度搜索',
              'url': 'https://www.baidu.com/'
            },
            {
              'type': 'view',
              'name': '腾讯网',
              'url': 'https://www.qq.com/'
            }
          ]
        },
      });
      if (result.data.errcode !== 0) {
        this.ctx.logger.error(`创建自定义菜单出错。errcode:${result.data.errcode}，errmsg:${result.data.errmsg}`);
      }
      return result;
    }
  }
}

module.exports = WechatService;
